package edu.zjut.hjg.saas.biz.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import edu.zjut.hjg.saas.biz.dao.UserDao;
import edu.zjut.hjg.saas.biz.model.User;
import edu.zjut.hjg.saas.biz.support.RoleName;

public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao {

    @Override
    public Integer create(User user) {
        return (Integer) getSqlMapClientTemplate().insert("user.create", user);
    }

    @Override
    public User findByAppIdAndLoginId(int appId, String loginId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appId", appId);
        params.put("loginId", loginId);
        return (User) getSqlMapClientTemplate()
                .queryForObject("user.findByAppIdAndLoginId", params);
    }

    @Override
    public User loadNotDeleted(int id) {
        return (User) getSqlMapClientTemplate().queryForObject("user.loadNotDeleted", id);
    }

    @Override
    public void update(User user) {
        getSqlMapClientTemplate().update("user.update", user);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> listByRoleNameAndAppId(RoleName roleName, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appId", appId);
        params.put("roleName", roleName);
        return getSqlMapClientTemplate().queryForList("user.listByRoleNameAndAppId", params);
    }

    @Override
    public void deleteByIdAndAppId(int id, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appId", appId);
        params.put("id", id);
        params.put("deleteVersion", (int) System.currentTimeMillis());
        getSqlMapClientTemplate().update("user.deleteByIdAndAppId", params);
    }

    @Override
    public User findByIdAndAppId(int id, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appId", appId);
        params.put("id", id);
        return (User) getSqlMapClientTemplate().queryForObject("user.findByIdAndAppId", params);
    }
}
